package com.jy.web.diy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.web.diy.entity.AttributeEntity;
import com.jy.web.diy.entity.BaseInfoEntity;
import com.jy.web.diy.service.AttributeService;
import com.jy.web.diy.service.BaseInfoService;
import com.jy.web.diy.service.JsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jy.web.diy.dao.CategoryDao;
import com.jy.web.diy.entity.CategoryEntity;
import com.jy.web.diy.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private JsonService jsonService;
    @Autowired
    private AttributeService attributeService;

    /**
     * @Author: JuiceYan
     * @Description: 重写removeByIds方法，依次删除json->baseInfo->attribute->category
     * @param: [idList]
     * @return: boolean
     * @throws:
     * @Date: 9:56 2019/1/6
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        Optional.ofNullable(idList).ifPresent(ids -> {
            LambdaQueryWrapper<BaseInfoEntity> queryWrapper = new LambdaQueryWrapper<BaseInfoEntity>().in(BaseInfoEntity::getCategoryId, ids);
            List<BaseInfoEntity> baseInfoEntities = baseInfoService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(baseInfoEntities)) {
                List<String> jsonIds = baseInfoEntities.stream().map(BaseInfoEntity::getId).collect(Collectors.toList());
                jsonService.removeByIds(jsonIds);
                baseInfoService.removeByIds(jsonIds);
            }
            LambdaQueryWrapper<AttributeEntity> attributeEntityLambdaQueryWrapper = new LambdaQueryWrapper<AttributeEntity>().in(AttributeEntity::getCategoryId, ids);
            attributeService.remove(attributeEntityLambdaQueryWrapper);
        });
        LambdaQueryWrapper<CategoryEntity> categoryEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryEntityLambdaQueryWrapper.in(CategoryEntity::getId, idList);
        remove(categoryEntityLambdaQueryWrapper);
        return true;
    }
}
